﻿
// #define TRIAL
#if TRIAL && !DEBUG
Disable "#define TRIAL" for Release build.
#endif

// #define DEBUG_LOCALIZATION
#if DEBUG_LOCALIZATION && !DEBUG
Disable "#define DEBUG_LOCALIZATION" for Release build.
#endif

using EmperialApps.WeatherSpark.Internal;
using EmperialApps.WeatherSpark.Resources;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Markup;
using System.Windows.Navigation;

namespace EmperialApps.WeatherSpark {

    public partial class App : Application {

        /// <summary>
        /// Gets a value indicating whether the application was built using a Debug configuration.
        /// </summary>
#if DEBUG
        public const bool IsDebug = true;
#else
        public const bool IsDebug = false;
#endif

        private static bool? _isTrial;

        /// <summary>
        /// Gets a value indicating whether the application is in trial mode.
        /// </summary>
        public static bool IsTrial {
            get {
                if( !App._isTrial.HasValue )
#if TRIAL
                    App._isTrial = true;
#else
                    App._isTrial = new Microsoft.Phone.Marketplace.LicenseInformation( ).IsTrial( );
#endif

                return App._isTrial.Value;
            }
#if DEBUG
            set { App._isTrial = value; }
#endif
        }

        /// <summary>
        /// Provides easy access to the root frame of the Phone Application.
        /// </summary>
        /// <returns>The root frame of the Phone Application.</returns>
        public PhoneApplicationFrame RootFrame { get; private set; }

        /// <summary>
        /// Constructor for the Application object.
        /// </summary>
        public App( ) {
            // Global handler for uncaught exceptions.
            UnhandledException += Application_UnhandledException;

            // Standard Silverlight initialization
            InitializeComponent( );

            // Phone-specific initialization
            InitializePhoneApplication( );

            // Language display initialization
            InitializeLanguage( );

            // Show graphics profiling information while debugging.
            if( System.Diagnostics.Debugger.IsAttached ) {
                // Display the current frame rate counters.
                Application.Current.Host.Settings.EnableFrameRateCounter = true;

                //MetroGridHelper.IsVisible = true;

                // Show the areas of the app that are being redrawn in each frame.
                //Application.Current.Host.Settings.EnableRedrawRegions = true;

                // Enable non-production analysis visualization mode,
                // which shows areas of a page that are handed off to GPU with a colored overlay.
                //Application.Current.Host.Settings.EnableCacheVisualization = true;

                // Disable the application idle detection by setting the UserIdleDetectionMode property of the
                // application's PhoneApplicationService object to Disabled.
                // Caution:- Use this under debug mode only. Application that disables user idle detection will continue to run
                // and consume battery power when the user is not using the phone.
                var service = PhoneApplicationService.Current;
                if( service != null )
                    service.UserIdleDetectionMode = IdleDetectionMode.Disabled;
            }

#if CLIENT_HTTP
            // Register alternate HTTP stack (http://www.benday.com/2010/08/16/how-to-permanently-banish-silverlights-not-found-error-for-wcf-service-calls/)
            bool registerResult = System.Net.WebRequest.RegisterPrefix( "http://", System.Net.Browser.WebRequestCreator.ClientHttp );
            System.Diagnostics.Debug.Assert( registerResult );
#endif
        }

        // Code to execute when the application is launching (eg, from Start)
        // This code will not execute when the application is reactivated
        private void Application_Launching( object sender, LaunchingEventArgs e ) {
            App._isTrial = null;
        }

        // Code to execute when the application is activated (brought to foreground)
        // This code will not execute when the application is first launched
        private void Application_Activated( object sender, ActivatedEventArgs e ) {
#if !TRIAL
            App._isTrial = null;
#endif
        }

        // Code to execute when the application is deactivated (sent to background)
        // This code will not execute when the application is closing
        private void Application_Deactivated( object sender, DeactivatedEventArgs e ) {
            Settings.UpdateTileAgent( );
        }

        // Code to execute when the application is closing (eg, user hit Back)
        // This code will not execute when the application is deactivated
        private void Application_Closing( object sender, ClosingEventArgs e ) {
            Settings.UpdateTileAgent( );
        }

        // Code to execute if a navigation fails
        private void RootFrame_NavigationFailed( object sender, NavigationFailedEventArgs e ) {
            // A navigation has failed; break into the debugger
            if( System.Diagnostics.Debugger.IsAttached )
                System.Diagnostics.Debugger.Break( );
        }

        // Code to execute on Unhandled Exceptions
        private void Application_UnhandledException( object sender, ApplicationUnhandledExceptionEventArgs e ) {
            // An unhandled exception has occurred; break into the debugger
            if( System.Diagnostics.Debugger.IsAttached )
                System.Diagnostics.Debugger.Break( );

            e.ExceptionObject.Record( );
        }

        #region Phone application initialization

        // Avoid double-initialization
        private bool phoneApplicationInitialized = false;

        // Do not add any additional code to this method
        private void InitializePhoneApplication( ) {
            if( phoneApplicationInitialized )
                return;

            // Create the frame but don't set it as RootVisual yet; this allows the splash
            // screen to remain active until the application is ready to render.
            RootFrame = new TransitionFrame( );
            RootFrame.Navigated += CompleteInitializePhoneApplication;

            // Handle navigation failures
            RootFrame.NavigationFailed += RootFrame_NavigationFailed;

            // Ensure we don't initialize again
            phoneApplicationInitialized = true;
        }

        // Do not add any additional code to this method
        private void CompleteInitializePhoneApplication( object sender, NavigationEventArgs e ) {
            // Set the root visual to allow the application to render
            if( RootVisual != RootFrame )
                RootVisual = RootFrame;

            // Remove this handler since it is no longer needed
            RootFrame.Navigated -= CompleteInitializePhoneApplication;
        }

        #endregion

        // Initialize the app's font and flow direction as defined in its localized resource strings.
        private void InitializeLanguage( ) {
            try {
#if DEBUG_LOCALIZATION
                var culture = new CultureInfo( "zh-CN" ); //"de-AT" );
                var thread = System.Threading.Thread.CurrentThread;
                thread.CurrentCulture = thread.CurrentUICulture = culture;
                System.Diagnostics.Debug.WriteLine( "ResourceLanguage: " + AppResources.ResourceLanguage );
#endif
                LogResources.Culture = new CultureInfo( "en-US" );

                // Set the font to match the display language defined by the
                // ResourceLanguage resource string for each supported language.
                //
                // Fall back to the font of the neutral language if the Display
                // language of the phone is not supported.
                //
                // If a compiler error is hit then ResourceLanguage is missing from
                // the resource file.
                RootFrame.Language = XmlLanguage.GetLanguage( AppResources.ResourceLanguage );

                // Set the FlowDirection of all elements under the root frame based
                // on the ResourceFlowDirection resource string for each
                // supported language.
                //
                // If a compiler error is hit then ResourceFlowDirection is missing from
                // the resource file.
                FlowDirection flow = (FlowDirection)Enum.Parse( typeof( FlowDirection ), AppResources.ResourceFlowDirection );
                RootFrame.FlowDirection = flow;
            }
            catch {
                // If an exception is caught here it is most likely due to either
                // ResourceLangauge not being correctly set to a supported language
                // code or ResourceFlowDirection is set to a value other than LeftToRight
                // or RightToLeft.

                if( System.Diagnostics.Debugger.IsAttached )
                    System.Diagnostics.Debugger.Break( );

                throw;
            }
        }

    }

}
